<?php
Yii::import('application.mlm.core.board.arr_multisort');
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
*/

class Unit_testController extends Controller {

    function actionresult() {

        $sql = "SELECT network_id FROM sys_network ORDER BY network_id DESC limit 2";
        $result = Yii::app()->db->createCommand($sql)->queryAll();
        
        echo "<pre>";
        print_r($result);

        echo $result[1]['network_id']."----".$result[0]['network_id'];
    }

    function actioncekspo() {

        $arr = array("802","803","804","805","806","807","810","811","812","813","829","834","835","836","837");

        foreach ($arr as $member_id) {
            $kualifikasi['sponsor'][$member_id]['member_id'] = $member_id;
            $kualifikasi['sponsor'][$member_id]['jumlah_sponsor'] = $this->get_number_of_sponsor($member_id, $board_id, $board_class);
            $kualifikasi['sponsor'][$member_id]['id_join'] = $this->get_id_join($member_id, $class);

            $kualifikasi_prioritas = $this->get_prioritas($member_id, $board_id, $board_class);

            $kualifikasi['prioritas'][$member_id]['member_id'] = $member_id;
            $kualifikasi['prioritas'][$member_id]['jumlah_roll'] = $kualifikasi_prioritas['jumlah_roll'];
            $kualifikasi['prioritas'][$member_id]['jumlah_sponsor'] = $kualifikasi_prioritas['jumlah_sponsor'];
            $kualifikasi['prioritas'][$member_id]['id_join'] = $this->get_id_join($member_id, $class);
            //masukkan ke roll

        }
        //instance arr_multi sort-nya
        $sort_sponsor = new arr_multisort();
        $sort_sponsor->setArray($kualifikasi['sponsor']);
        //sort action
        $sort_sponsor->addColumn('jumlah_sponsor', SRT_DESC);
        $sort_sponsor->addColumn('id_join', SRT_ASC);
        $peringkat_sponsor = $sort_sponsor->sort();
        //buat perioritas
        $sort_perioritas = new arr_multisort();
        $sort_perioritas->setArray($kualifikasi['prioritas']);
        $sort_perioritas->addColumn('jumlah_sponsor', SRT_DESC);
        $sort_perioritas->addColumn('jumlah_roll', SRT_DESC);
        $sort_perioritas->addColumn('id_join', SRT_ASC);
        $peringkat_perioritas = $sort_perioritas->sort();

        $member_prioritas = "";
        foreach ($peringkat_perioritas as $key => $val) {
            if ($val['jumlah_sponsor'] >= 3 && $val['jumlah_roll'] >= 1) {
                $member_prioritas = $val['member_id'];
                break;
            } elseif ($val['jumlah_sponsor'] == 2 && $val['jumlah_roll'] >= 2) {
                $member_prioritas = $val['member_id'];
                break;
            } elseif ($val['jumlah_sponsor'] == 1 && $val['jumlah_roll'] >= 3) {
                $member_prioritas = $val['member_id'];
                break;
            } elseif ($val['jumlah_sponsor'] == 0 && $val['jumlah_roll'] >= 5) {
                $member_prioritas = $val['member_id'];
                break;
            }
        }
        // buat urutan peringkat untuk dijadikan class baru
        // level 1 pertama diambil dari peringkat sponsor
        // jika ada member prioritas, level 1 kedua diambil dari member prioritas,jika tidak maka diambil dari urutuan sponsor no 2

        if (!empty($member_prioritas)) {
            $urutan[0] = $member_prioritas;
        } else {
            $urutan[0] = $peringkat_sponsor[0]['member_id'];
        }
        $index = 1;
        foreach ($peringkat_sponsor as $key => $val) {
            if ($val['member_id'] != $urutan[0]) {
                $urutan[$index] = $val['member_id'];
                $index++;
            }
        }

        $group_1 = array($urutan[0], $urutan[2], $urutan[3]);
        $group_2 = array($urutan[1], $urutan[4], $urutan[5]);
        $index_key = 0;
        foreach ($urutan as $key => $val) {
            if ($key >= 6) {
                //$sponsor = $db->GetOne("select network_log_sponsor from $network_log_tabel where network_log_mid = '" . $val . "'");
                $sponsor = function_lib::get_one('board_network_log_sponsor_board_network_id', 'sys_board_network_log', 'board_network_log_board_network_id = \'' . $val . '\'');
                $value_1 = (in_array($sponsor, $group_1)) ? "1" : "0";
                $value_2 = (in_array($sponsor, $group_2)) ? "1" : "0";
                if ($value_1 == "1" && $value_2 == "0") {
                    if (count($anggota[1]) < 4) {
                        $anggota[1][$index_key]['board_network_id'] = $val;
                        $anggota[1][$index_key]['key'] = $key;
                        $anggota[1][$index_key]['sponsor'] = $sponsor;
                    } else {
                        $anggota_cad[1][$index_key]['board_network_id'] = $val;
                        $anggota_cad[1][$index_key]['key'] = $key;
                        $anggota_cad[1][$index_key]['sponsor'] = $sponsor;
                    }
                    //}elseif( $value_2 == "1" && $value_1=="0" ){
                } elseif ($value_2 == "1" && $value_1 == "0") {
                    if (count($anggota[2]) < 4) {
                        $anggota[2][$index_key]['board_network_id'] = $val;
                        $anggota[2][$index_key]['key'] = $key;
                        $anggota[2][$index_key]['sponsor'] = $sponsor;
                    } else {
                        $anggota_cad[1][$index_key]['board_network_id'] = $val;
                        $anggota_cad[1][$index_key]['key'] = $key;
                        $anggota_cad[1][$index_key]['sponsor'] = $sponsor;
                    }
                } else {

                    $anggota_cad[1][$index_key]['board_network_id'] = $val;
                    $anggota_cad[1][$index_key]['key'] = $key;
                    $anggota_cad[1][$index_key]['sponsor'] = $sponsor;
                }
            }
            $index_key++;
        }

        echo "<pre>";
        print_r($peringkat_sponsor);
//    echo "==========&&&&&&=============";
//    print_r($anggota);
//    echo "</pre>";
//    die();
        @sort($anggota_cad[1]);
        @sort($anggota[1]);
        @sort($anggota[2]);

        foreach ($anggota_cad[1] as $key => $val) {
            if (count($anggota[1]) < 4) {
                $anggota[1][] = $anggota_cad[1][$key];
            } else {
                $anggota[2][] = $anggota_cad[1][$key];
            }
        }

        $urutan[6] = $anggota[1][0]['board_network_id'];
        $urutan[7] = $anggota[1][1]['board_network_id'];
        $urutan[8] = $anggota[1][2]['board_network_id'];
        $urutan[9] = $anggota[1][3]['board_network_id'];

        $urutan[10] = $anggota[2][0]['board_network_id'];
        $urutan[11] = $anggota[2][1]['board_network_id'];
        $urutan[12] = $anggota[2][2]['board_network_id'];
        $urutan[13] = $anggota[2][3]['board_network_id'];
        //buat jaringanya
        //class 1
        $board_leader_1 = $urutan[0];
        $board_member_group_1 = ' '.$urutan[0] . " | " . $urutan[2] . " | " . $urutan[3] . " | " . $urutan[6] . " | " . $urutan[7] . " | " . $urutan[8] . " | " . $urutan[9]." ";
        $board_start_date_1 = date("Y-m-d H:i:s");

        //class 2
        $board_leader_2 = $urutan[1];
        $board_member_group_2 = ' '.$urutan[1] . " | " . $urutan[4] . " | " . $urutan[5] . " | " . $urutan[10] . " | " . $urutan[11] . " | " . $urutan[12] . " | " . $urutan[13]." ";
        $board_start_date_2 = date("Y-m-d H:i:s");
        echo $board_member_group_1;
        echo "<br>";
        echo $board_member_group_2;
//        foreach($arr as $id ) {
//            $sql = "select count(*) as jumlah from sys_board_network_log where board_network_log_sponsor_board_network_id = '$id' and board_network_log_input_datetime <= '2012-01-13 14:16:39'";
//            $jumlah = Yii::app()->db->CreateCommand($sql)->queryScalar();
//            $sql = "select board_network_network_mid from sys_board_network where board_network_id = '$id'";
//            $mid = Yii::app()->db->CreateCommand($sql)->queryScalar();
//            echo "$mid # $id => $jumlah <br>";
//
//
//
//        }



    }



    public function actionCekupline() {
        $mid = function_lib::uri_segment(3);

    }

    public function actionRekapewallet() {
//        $sql = "select * from sys_ewallet where ewallet_cash_acc > 0";
//        $result = Yii::app()->db->createCommand($sql)->queryAll();
//        foreach($result as $row){
//            $cash = Yii::app()->db->createCommand("SELECT SUM(ewallet_income_cash) FROM sys_ewallet_income WHERE ewallet_income_network_id = '".$row['ewallet_network_id']."'")->queryScalar();
//            $product = Yii::app()->db->createCommand("SELECT SUM(ewallet_income_products) FROM sys_ewallet_income WHERE ewallet_income_network_id = '".$row['ewallet_network_id']."'")->queryScalar();
//            $voucher = Yii::app()->db->createCommand("SELECT SUM(ewallet_income_voucher) FROM sys_ewallet_income WHERE ewallet_income_network_id = '".$row['ewallet_network_id']."'")->queryScalar();
//
//            $update = "UPDATE sys_ewallet SET
//                        ewallet_cash_acc = '".$cash."',
//                        ewallet_products_acc = '".$product."',
//                        ewallet_voucher_acc = '".$voucher."'
//                        WHERE ewallet_network_id = '".$row['ewallet_network_id']."'
//                        ";
//            Yii::app()->db->createCommand($update)->Execute();
//        }
    }

//    public function actionUpdateewallet(){
//
//        $sql = "SELECT *
//                FROM  `sys_ewallet_log`
//                WHERE  `ewallet_log_datetime` >  '2011-12-01 00:00:00'
//                AND  `ewallet_log_status` =  'debit'
//                AND  `ewallet_log_type` =  'cash'
//                AND  `ewallet_log_note` LIKE  '%Withdraw E-wallet cash sebesar %'";
//
//        $result = Yii::app()->db->createCommand($sql)->queryAll();
//
//        foreach($result as $row){
//            //delete datanya
//            Yii::app()->db->createCommand("delete from sys_ewallet_log where ewallet_log_id = '".$row['ewallet_log_id']."' ")->Execute();
//            //update ewalletnya
//            Yii::app()->db->createCommand("UPDATE sys_ewallet SET ewallet_cash_paid = ewallet_cash_paid - ".$row['ewallet_log_value']."
//                                                      WHERE ewallet_network_id = '".$row['ewallet_log_network_id']."'")->execute();
//        }
//
//    }

    public function actionTransfer_bonus() {
//            $data = "GI10000012,4508800
//            GI10000012-1,1319200
//            GI10000015,776000
//            GI10000018,232800
//            GI10000019,155200
//            GI10000021,4385608
//            GI10000028,783416
//            GI10000029,1242808
//            GI10000033,304000
//            GI10000057,1120000
//            GI10000171,232800
//            GI10000180,1346792
//            GI10000181,322472
//            GI10000182,479224
//            GI10000183,1253672
//            GI10000186,538200
//            GI10000194,455944
//            GI10000195,2153832
//            GI10000196,249528
//            GI10000210,3182808
//            GI10000211,1010008
//            GI10000212,949480
//            GI10000213,999144
//            GI10000214,1129512
//            GI10000215,758584
//            GI10000216,320000
//            GI10000227,1778248
//            GI10000235,1250568
//            GI10000236,525600
//            GI10000237,240000
//            GI10000249,572344
//            GI10000257,388000
//            GI10000278,310400
//            GI10000288,1186936
//            GI10000289,781864
//            GI10000290,234008
//            GI10000296,853600
//            GI10000298,310400
//            GI10000307,966552
//            GI10000308,393864
//            GI10000321,539000
//            GI10000322,232800
//            GI10000326,232800
//            GI10000337,400000
//            GI10000345,1020800
//            GI10000345-1,232800
//            GI10000391,163200
//            GI10000402,232800
//            GI10000417,698400
//            GI10000418,324024
//            GI10000434,440424
//            GI10000438,400000
//            GI10000442,400000
//            GI10000443,400000
//            GI10000454,318160
//            GI10000482,388000
//            GI10000497,1086400
//            GI10000499,943272
//            GI10000516,1450000
//            GI10000518,1078296
//            GI10000603,232800
//            GI10000604,931200
//            GI10000739,2905000
//            GI10000751,1003000
//            GI10000765,1241600
//            GI10000765-2,543200
//            GI10000766,1512856
//            GI10000813,232800
//            GI10000907,1164000
//            GI10000999,776000
//            GI10001000,1164000
//            GI10001001,1164000
//            GI10000753,388000
//            GI10000444,400000";
//            
//            $data_arr = explode("
//            ", $data);
//            
//            foreach ($data_arr as $data_transfer){
//                $explode = explode(",", $data_transfer);
//                echo $mid = $explode[0];
//                echo "<BR>";
//                $bonus = $explode[1];
//                
//                $network_id = function_lib::get_network_id($mid);
//                
//                echo $sql_ewallet = "UPDATE sys_ewallet set ewallet_cash_paid = ewallet_cash_paid + $bonus WHERE ewallet_network_id = '$network_id'";
//                echo "<BR>";
//                Yii::app()->db->createCommand($sql_ewallet)->execute();
//                        
//                echo $sql_ewallet_witdraw = "INSERT INTO sys_ewallet_withdrawal SET 
//                                        ewallet_withdrawal_network_id = '$network_id', 
//                                        ewallet_withdrawal_value = '$bonus', 
//                                        ewallet_withdrawal_datetime = '2011-12-01',
//                                        ewallet_withdrawal_is_approve ='1'
//                                        ";
//                echo "<BR>";
//                Yii::app()->db->createCommand($sql_ewallet_witdraw)->execute();
//                
//                echo $sql_ewallet_log = "INSERT INTO sys_ewallet_log SET 
//                                    ewallet_log_network_id = '$network_id',
//                                    ewallet_log_type = 'cash',
//                                    ewallet_log_value = '$bonus',
//                                    ewallet_log_status = 'credit',
//                                    ewallet_log_datetime = '2011-12-01',
//                                    ewallet_log_note = 'WITHDRAWAL BONUS'
//                                    ";
//                Yii::app()->db->createCommand($sql_ewallet_log)->execute();
//                echo "<BR>";
//            }
    }

    public static function getCurrentUrl() {
        $resUri = $newUri = $url = array();
        $url[] = Yii::app()->controller->id;
        $url[] = Yii::app()->controller->action->id;
        $finalUrl = join('/', $url);
        $replacement = 'r=' . $finalUrl;
        if (Yii::app()->urlManager->urlFormat == 'get') {
            $uri = explode('&', $_SERVER['QUERY_STRING']);
            foreach ($uri as $v) {
                if ($v != $replacement) {
                    $newUri[] = $v;
                }
            }

            if (count($newUri) > 0) {
                foreach ($newUri as $kv) {
                    $nn = explode('=', $kv);
                    $resUri[$nn[0]] = $nn[1];
                }
            }
            return Yii::app()->urlManager->createUrl($finalUrl, $resUri);
        } else {
            return $_SERVER['REQUEST_URI'];
        }
    }

    function actionGetUpline() {


        //echo $network_mid = "GI10000961";
//        $arr_mid = array("GI10000373", "GI10000374", "GI10000936", "GI10000937");
//        //$arr_mid = array("GI10000754", "GI10000444", "GI10000445", "GI10000446", "GI10000450");
//
//        foreach ($arr_mid as $network_mid) {
//            echo "====================================================================<br>";
//
//            $network_id = $up = function_lib::get_network_id($network_mid);
//            $tgl_join = function_lib::get_one("DATE(member_join_datetime)", "sys_member", "member_network_id = '$network_id'");
//            echo "MID = $network_mid $tgl_join";
//            $x = 1;
//            do {
//
//
//                $up = function_lib::get_network_sponsor_network_id($up);
//                $nama = function_lib::get_member_name($up);
//                $mid = function_lib::get_network_mid($up);
//
//                echo "<p>Sponso : $mid = $nama = $up</p>";
//
//                if ($x == 1) {
//                    //bonus sponsor
//                    $total_bonus = 500000;
//                    //insert bonus log
//                    $sql = "INSERT INTO sp_sponsor_bonus_log SET sponsor_bonus_log_network_id = '$up',
//                        sponsor_bonus_log_value = " . $total_bonus . ", sponsor_bonus_log_date = '$tgl_join'";
//                    Yii::app()->db->createCommand($sql)->execute();
//                    //masukkan ke ewallet
//                    $this->insert_ewallet($up, $bonus_value,$tgl_join,$bonus="sponsor");
//                } else {
//                    //bonus gen_extra_sponsor
//                    //bonus sponsor
//                    $total_bonus = 2000;
//                    //insert bonus log
//                    $sql = "INSERT INTO sp_gen_node_bonus_log SET gen_node_bonus_log_network_id = '$up',gen_node_bonus_log_level_depth='$x',
//                        gen_node_bonus_log_value = " . $total_bonus . ", gen_node_bonus_log_date = '$tgl_join'";
//                    Yii::app()->db->createCommand($sql)->execute();
//                    //masukkan ke ewallet
//                    $this->insert_ewallet($up, $bonus_value,$tgl_join,$bonus="gen_node");
//                }
//
//                $x++;
//            } while ($up != '0' && $x <= 11);
//        }
    }

    public function insert_ewallet($network_id, $bonus_value, $date, $bonus, $potongan_ewallet = 0.8) {
        //$now = date("Y-m-d H:i:s");
        $now = $date;
        $ewallet['products'] = $ewallet['cash'] = $ewallet['products'] = $ewallet['voucher'] = 0;
        //kurangi dulu dengan index dan admin fee
        //kurangi index
        $potongan_index = $bonus_value * 0 / 100;
        $bonus_value = $bonus_value - $potongan_index;
        //kurangi admin fee
        $admin_fee = $bonus_value * 3 / 100;
        $bonus_value = $bonus_value - $admin_fee;

        $sql_ewallet_cut = "INSERT INTO sys_ewallet_cut SET
                                ewallet_cut_network_id = '" . $network_id . "',
                                ewallet_cut_bonus_name = '" . $bonus . "',
                                ewallet_cut_index = '" . $potongan_index . "',
                                ewallet_cut_adm = '" . $admin_fee . "',
                                ewallet_cut_date = '$now'";
        Yii::app()->db->createCommand($sql_ewallet_cut)->execute();

        $ewallet['cash'] = intval(ceil($bonus_value * $potongan_ewallet));
        //total produknya masih di breakdown jadi 80% produk 20% voucher
        $produk_total = $bonus_value - $ewallet['cash'];
//        $ewallet['products'] = intval(ceil($produk_total * 0.8));
//        $ewallet['voucher'] = $produk_total - $ewallet['products'];
//        
        //perubahan system perhitungan komposisi ewallet
        //by wawan 25.11.2011

        $periode = substr($now, 0, 7);
        $jumlah_ewallet_produk = function_lib::get_one("sum(ewallet_income_products)", "sys_ewallet_income", "LEFT(ewallet_income_date,7)= '" . $periode . "' And ewallet_income_network_id = '" . $network_id . "'");
        $ewallet['products'] = $ewallet['products'] = $ewallet['voucher'] = 0;
        if ($jumlah_ewallet_produk < 500000) {
            $kekurangan = 500000 - $jumlah_ewallet_produk;
            if ($produk_total <= $kekurangan) {
                $ewallet['products'] = $produk_total;
            } else {
                $ewallet['products'] = $kekurangan;
                $ewallet['voucher'] = $produk_total - $kekurangan;
            }
        } else {
            $ewallet['voucher'] = $produk_total;
        }

        foreach ($ewallet as $jenis => $value) {
            $note = "Penambahan E-wallet " . $bonus . " Dengan jenis Ewallet : " . $jenis . " Senilai : Rp." . number_format($value);
            //tambah ke ewalletnya
            $sql_ewallet_log = "INSERT INTO sys_ewallet_log SET ewallet_log_network_id = '" . $network_id . "', ewallet_log_type = '" . $jenis . "', ewallet_log_value = '" . $value . "',
                            ewallet_log_status = 'credit', ewallet_log_datetime = '" . $now . "', ewallet_log_note = '" . $note . "'";
            Yii::app()->db->createCommand($sql_ewallet_log)->execute();
            //sekalian update ke sys_ewallet
            $sql_ewallet = "UPDATE sys_ewallet SET ewallet_" . $jenis . "_acc = ewallet_" . $jenis . "_acc + " . $value . " WHERE ewallet_network_id = '" . $network_id . "'";
            Yii::app()->db->createCommand($sql_ewallet)->execute();
        }

        $sql_ewallet_income = "INSERT INTO sys_ewallet_income SET
                                ewallet_income_network_id = '" . $network_id . "',
                                ewallet_income_bonus_name = '" . $bonus . "',
                                ewallet_income_cash = '" . $ewallet['cash'] . "', 
                                ewallet_income_noncash = '" . ($ewallet['products'] + $ewallet['voucher']) . "',
                                ewallet_income_products = '" . $ewallet['products'] . "',
                                ewallet_income_voucher = '" . $ewallet['voucher'] . "', 
                                ewallet_income_date = NOW() ";
        Yii::app()->db->createCommand($sql_ewallet_income)->execute();
    }

    /**
     * Method buat cari member prioritas
     */
    public function get_prioritas($board_network_id, $board_id, $board = '1') {
        $jumlah_roll = function_lib::get_one('COUNT(*)', 'sys_board_network_log LEFT JOIN sys_board_network ON board_network_log_board_network_id = board_network_id', 'board_network_log_board_network_id = \'' . $board_network_id . '\' AND board_network_board_class = \'' . $board . '\'');
        $jumlah_sponsor = $this->get_accumulative_sponsor($board_network_id);
        $data['jumlah_roll'] = $jumlah_roll;
        $data['jumlah_sponsor'] = $jumlah_sponsor;
        return $data;
    }

    /**
     * method buat cari jumlah akumulatif sponsor
     */
    private function get_accumulative_sponsor($member_network_id) {
        $network_id = function_lib::get_one('board_network_member_id', 'sys_board_network', 'board_network_id = \'' . $member_network_id . '\'');
        $accumulative_sponsor = function_lib::get_one('COUNT(*)', 'sys_network', 'network_sponsor_network_id = \'' . $network_id . '\'');
        return $accumulative_sponsor;
    }

    /**
     * Buat Ngambil berapa jumlah sponsornya
     * @param int $board_network_id
     * @param int $board_id promary key dari board-idnya
     * @param int $board_class
     */
    private function get_number_of_sponsor($board_network_id, $board_id, $board_class = '1') {
        $jumlah_sponsor = function_lib::get_one('COUNT(*)', 'sys_board_network_log', 'board_network_log_sponsor_board_network_id = \'' . $board_network_id . '\'');
        return $jumlah_sponsor;
    }

    /**
     * method buat cari kapan ID joinnya
     * @param int $board_network_id
     * @param int $board_id
     */
    private function get_id_join($board_network_id, $board_id) {
        $value = function_lib::get_one('board_network_log_id', 'sys_board_network_log', 'board_network_log_board_id = \'' . $board_id . '\' AND
                                                                                         board_network_log_board_network_id = \'' . $board_network_id . '\'');
        return $value;
    }
}

?>
